package br.com.merks.service;

import java.util.List;

import javax.persistence.EntityManager;

import org.apache.log4j.Logger;

import br.com.caelum.vraptor.ioc.Component;
import br.com.caelum.vraptor.util.jpa.EntityManagerCreator;
import br.com.merks.model.Category;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
@Component
public class CategoryServiceImpl implements CategoryService {
	public static final Logger logger = Logger.getLogger(CategoryServiceImpl.class);
	private EntityManager entityManager;
	private MailService mailService;
	public CategoryServiceImpl(EntityManagerCreator emCreator, MailService mailService) {
		this.entityManager = emCreator.getInstance();
		this.mailService = mailService;
	}
	public Category add(Category category) {
		this.entityManager.getTransaction().begin();
		this.entityManager.persist(category);
		this.entityManager.getTransaction().commit();
		return category;
	}

	public Category delete(Category category) {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		com.google.appengine.api.datastore.Query query = new Query("Category",KeyFactory.createKey("Category", category.getId()));
		 for (Entity taskEntity : datastore.prepare(query).asIterable()) {
			 datastore.delete(taskEntity.getKey());
		 }
		return category;
	}

	public Category find(Category category) {
		return this.entityManager.find(Category.class, category.getId());
	}

	public List<Category> list() {
		return (List<Category>) this.entityManager.createNamedQuery("category.findAll").getResultList();
	}

}
